package com.asia.algorithmcode.slideWindow;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @DESCRIPTION: 76
 * @USER: wanfu
 * @DATE: 2025/3/25 星期二 10:18
 */
public class MinWindow {

    public static void main(String[] args) {
        String s = "ADOBECODEBANC";
        String t = "ABC";
        System.out.println(new MinWindow().minWindow(s, t));
    }

    Map<Character, Integer> ori = new HashMap<Character, Integer>();
    Map<Character, Integer> cnt = new HashMap<Character, Integer>();

    public String minWindow(String s, String t) {
        int tLength = t.length();
        for (int i = 0; i < tLength; i++) {
            ori.put(t.charAt(i), ori.getOrDefault(t.charAt(i), 0) + 1);
        }
        int l = 0;
        int r = -1;
        int resL = -1;
        int resR = -1;
        int length = Integer.MAX_VALUE;
        int sLength = s.length();
        while (r < sLength) {
            ++r;
            if (r < s.length() && ori.containsKey(s.charAt(r))) {
                cnt.put(s.charAt(r), cnt.getOrDefault(s.charAt(r), 0) + 1);
            }
            while (check() && l <= r) {
                if (r - l + 1 < length) {
                    length = r - l + 1;
                    resR = r;
                    resL = l;
                }
                if (cnt.containsKey(s.charAt(l))) {
                    cnt.put(s.charAt(l), cnt.getOrDefault(s.charAt(l), 0) - 1);
                }
                ++l;
            }
        }
        return resR == -1 ? "" : s.substring(resL, resR + 1);
    }

    /**
     * 检查当前ori的所有字符和对应个数在cnt哈希表中是否都出现
     *
     * @return
     */
    public boolean check() {
        for (Character c : ori.keySet()) {
            Integer i = ori.get(c);
            if (!cnt.containsKey(c) || cnt.get(c) < i) {
                return false;
            }
        }
        return true;
    }


}
